
import 'dart:async';
import 'dart:convert';
import 'package:todo_app/controllers/definitions/Definition.dart';

import 'ApiService.dart';

class OAuthController {
    static String passwordTokenPath = "/api/common/upload";
    /// 1. 根据password校验
    static Future<OAuthResponse> passwordToken(String username, String password) async {
      var param = OAuthParam(username: username, password: password);
      var response = await ApiService.post("/oauth/token", param.toJson(), OAuthParam.header);
      var r = OAuthResponse()..fromJson(response.data);
      return r;
    }
}

class OAuthParam extends Definition {

  OAuthParam({
    this.password,
    this.username
  });

  String? password;
  String? username;
  String? grantType = "password";
  String? scope = "server";

  static String? clientID = "admin";
  static String? clientSecret = "admin";

  @override
  void fromJson(Map<String, dynamic> json) {
    grantType = json['grant_type'];
    if(grantType == 'password') {
      username = json['username'];
      password = json['password'];
    }
    if(json['scope']) scope = json['scope'];
  }

  @override
  Map<String, dynamic> toJson() {
    return {
      'username': username,
      'password': password,
      'grant_type': grantType,
      'scope': scope
    };
  }

  static Map<String, dynamic> get header {
      var basicBase64 = base64.encode(("$clientID:$clientSecret").codeUnits);
      return {
        "Authorization": "Basic $basicBase64",
        'Content-Type': 'application/x-www-form-urlencoded'
      };
  }
}


class OAuthResponse extends Definition {
  String? accessToken;
  DateTime? accessTokenExpiresAt;
  String? refreshToken;
  DateTime? refreshTokenExpiresAt;
  String? scope;
  Map<String, dynamic>? client;
  Map<String, dynamic>? user;

  get userId {
    return user?.containsKey("id") == true ? user!['id'] : null;
  }
  
  @override
  void fromJson(Map<String, dynamic> json) {
    accessToken = json["accessToken"];
    accessTokenExpiresAt = DateTime.tryParse(json['accessTokenExpiresAt']);
    refreshToken = json["refreshToken"];
    refreshTokenExpiresAt = DateTime.tryParse(json['refreshTokenExpiresAt']);
    scope = json["scope"];
    client = json["client"];
    user = json["user"];
  }
  
  @override
  Map<String, dynamic> toJson() {
    return {};
  }
}

class ResultOAuthResponse extends Definition {
  
	String? status;
	OAuthResponse? data;
	String? msg;

  @override
  Map<String, dynamic> toJson() {
    return {
			"status": status,
			"data": data?.toJson(),
			"msg": msg,
    };
  }

  @override
  void fromJson(Map<String, dynamic> json) {
		status = json["status"];
		data = json["data"] == null ? null : (OAuthResponse()..fromJson(json["data"]));
		msg = json["msg"];
  }
  
}